package com.scau.phr.business.message.service;

import com.scau.phr.domain.entity.PhrMessage;
import com.scau.phr.domain.mapper.PhrMessageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 站内消息服务
 * @author yuzhiyi
 * @date 2018/8/13 11:19
 */
@Service
public class MessageService {

	@Autowired
	PhrMessageMapper mapper;

	/**
	 *
	 * @param sender    发送者
	 * @param receiver  接受者
	 * @param content   内容
	 * @param type      类型
	 * @param sendTime 可以指定sendTime延迟发送
	 */
	public PhrMessage addMessage(String sender, String receiver, String content, String type, LocalDateTime sendTime){
		LocalDateTime now = LocalDateTime.now();
		//如果sendTime小于当前的时间，将当前时间作为发送时间
		sendTime = sendTime.compareTo(now) < 0 ? now : sendTime;
		PhrMessage message = new PhrMessage();
		message.setSender(sender);
		message.setReceiver(receiver);
		message.setContent(content);
		message.setMessageType(type);
		message.setSendTime(sendTime);
		message.setReaded(false);
		mapper.insert(message);
		return message;
	}


	/**
	 * 用于增量更新
	 * 获取|__time__________now|
	 * @param tel
	 * @param time
	 * @return
	 */
	public Object getMessageAfterSendTime(String tel,LocalDateTime time){
		String stime = time.format(DateTimeFormatter.ISO_DATE_TIME);
		return mapper.listMessageAfterSendTime(tel,stime);
	}

	/**
	 * 获得用户当前收到的所有信息
	 * @param userTel
	 * @return
	 */
	public Object getAllMessage(String userTel){
		return mapper.listMessageByTel(userTel);
	}


	/**
	 * 将某条信息设置为已读
	 * @param id 信息ID
	 */
	public void markMessageReaded(Long id){
		mapper.makeMessageReadedById(id);
	}



}
